package com.fpx.open.platform.domain;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import javax.xml.bind.annotation.XmlTransient;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;

/**
 * 基础实体类，需要查询的实体类需要继承此类
 * 
 * @author sunkey
 * @date Mar 20, 2013 6:50:36 PM
 * @version 1.0.0 
 * @copyright fpx.com 
 */
public class BaseDomain extends ParentDomain implements Serializable{

	/**
	 * 
	 */
	private static final long serialVersionUID = 3741355731787357763L;
	
	/**
	 * 动态字段. 在ibatis文件中可用“dynamicFields.xxx”方式读取动态字段值
	 */
	protected Map<String, Object> dynamicFields = new HashMap<String, Object>();
	
	/** 最大行数.	 */
	private static final int MAX_ROWS = 9999999;
	
	/** 起始行数（oracle物理行号从1开始）.*/
	private int start = 1;

	/**
	 * 结束行数（如果不设置结束行，缺省查所有满足条件记录）.
	 */
	private int end = MAX_ROWS;

	/**
	 * 排序字段(例sp.spCode).
	 */
	private String sort;

	/**
	 * 正序|反序(例ASC).
	 */
	@XmlTransient
	private String order;
	
	/**
	 * 设置动态字段值.
	 * 
	 * @param fieldName
	 *            字段名称
	 * @param value
	 *            字段值
	 */
	@JsonAnySetter
	public void setField(String fieldName, Object value) {
		dynamicFields.put(fieldName, value);
	}
	
	/**
	 * 获取动态字段 Map
	 * @return
	 */
	@JsonAnyGetter
    public Map<String,Object> getDynamicMaps() {
        return dynamicFields;
    }
	
	/**
	 * 返回动态字段值.
	 * 
	 * @param fieldName
	 *            字段名称
	 * @return 对象
	 */
	public Object getField(String fieldName) {
		if (dynamicFields == null) {
			return null;
		}
		return dynamicFields.get(fieldName);
	}
	
	public String toString(){
		return ToStringBuilder.reflectionToString(this,ToStringStyle.MULTI_LINE_STYLE);
	}

	public int getStart() {
		return start;
	}

	public void setStart(int start) {
		this.start = start;
	}

	public int getEnd() {
		return end;
	}

	public void setEnd(int end) {
		this.end = end;
	}

	public String getSort() {
		return sort;
	}

	public void setSort(String sort) {
		this.sort = sort;
	}

	public String getOrder() {
		return order;
	}

	public void setOrder(String order) {
		this.order = order;
	}
	
	public void setPageInfo(int totalCount, int pageSize, int pageNo) {
		// 计算总页数
		int totalPage = totalCount / pageSize;
		if (totalCount % pageSize != 0) {
			totalPage = totalPage + 1;
		}
		if (pageNo > totalPage) {
			pageNo = totalPage;
		} else if (pageNo <= 0) {
			pageNo = 1;
		}
		
		int beginIndex = (pageNo - 1) * pageSize + 1;
		int endIndex = pageNo * pageSize;
		
		this.setStart(beginIndex);
		this.setEnd(endIndex);
	}

}
